package com.tyx.modules.manage.service.impl;

import com.tyx.common.exception.EffStateEnum;
import com.tyx.common.exception.ErrorEnum;
import com.tyx.common.exception.ServiceException;
import com.tyx.modules.manage.entity.PractitionersModel;
import com.tyx.modules.manage.entity.UserOperationEntity;
import com.tyx.modules.manage.service.UserOperationService;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tyx.common.utils.PageUtils;
import com.tyx.common.utils.Query;

import com.tyx.modules.manage.dao.PractitionersDao;
import com.tyx.modules.manage.entity.PractitionersEntity;
import com.tyx.modules.manage.service.PractitionersService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;


@Service("practitionersService")
public class PractitionersServiceImpl extends ServiceImpl<PractitionersDao, PractitionersEntity> implements PractitionersService {

    @Autowired
    private UserOperationService userOperationService;
    @Autowired
    private PractitionersDao practitionersDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String name = (String)params.get("name");
        IPage<PractitionersEntity> page = this.page(
                new Query<PractitionersEntity>().getPage(params),
                new QueryWrapper<PractitionersEntity>()
                        .like(StringUtils.isNotBlank(name),"name", name)
        );
        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params, Long userId) throws ServiceException {
        String name = (String)params.get("name");
        UserOperationEntity userOperationEntity = userOperationService.getOne(new QueryWrapper<UserOperationEntity>().eq("user_id",userId));
        if(userOperationEntity == null){
            throw new ServiceException(ErrorEnum.INFOEMPTY);
        }
        IPage<PractitionersModel> page = new Query<PractitionersModel>().getPage(params);
        QueryWrapper<PractitionersModel> query = new QueryWrapper();
        query.eq("a.corporate_id",userOperationEntity.getOperationId()).eq("cancel",0);
        if(StringUtils.isNotEmpty(name)){
            query.and(i ->i.like(StringUtils.isNotBlank(name),"a.name", name)
                    .or(g->g.like(StringUtils.isNotBlank(name),"a.id_card", name)));
        }
        page = practitionersDao.queryAllByOpId(page,query);
        return new PageUtils(page);
    }

    @Override
    public void saveData(PractitionersEntity practitionersEntity, Long userId) throws ServiceException {
        practitionersEntity.setSubTime(new Date());//设置提交时间为当前系统时间
        practitionersEntity.setUpdateUser(userId);
        practitionersEntity.setUpdateTime(new Date());
        practitionersEntity.setSubUser(userId);//获取当前登陆用户id
        UserOperationEntity userOperationEntity = userOperationService.getOne(new QueryWrapper<UserOperationEntity>().eq("user_id",userId));
        if(userOperationEntity == null){
            throw new ServiceException(ErrorEnum.INFOEMPTY);
        }
        practitionersEntity.setCorporateId(userOperationEntity.getOperationId());
        this.save(practitionersEntity);
    }

    @Override
    public List<PractitionersModel> getListByName(String name) {
        List<PractitionersModel> list = practitionersDao.queryList(new QueryWrapper<PractitionersModel>().like("name",name));
        for (PractitionersModel practitionersModel:list){
            String idCard = practitionersModel.getIdCard().replaceAll("(\\d{4})\\d{10}(\\w{4})","$1*****$2");
            String phone = practitionersModel.getPhone().replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2");
            practitionersModel.setAddr(null);
            practitionersModel.setEffStateValue(EffStateEnum.getName(practitionersModel.getEffState()));
            practitionersModel.setEffState(null);
            practitionersModel.setIdCard(idCard);
            practitionersModel.setSubTime(null);
            practitionersModel.setUpdateTime(null);
            practitionersModel.setPhone(phone);
        }
        return list;
    }

    @Override
    public void updateData(PractitionersEntity params, Long userId) {
        params.setUpdateTime(new Date());//设置修改时间为当前系统时间
        params.setUpdateUser(userId);//获取当前登陆用户id
        this.updateById(params);
    }

    @Override
    public void cancel(PractitionersEntity practitionersEntity) {
        practitionersEntity.setCancel("1");
        this.updateById(practitionersEntity);
    }
    @Override
    @Transactional(readOnly = false,rollbackFor = Exception.class)
    public boolean batchImport(String fileName, MultipartFile file) throws Exception {
        DateFormat dataFormat = new SimpleDateFormat("yyyy-MM-dd");

        boolean notNull = false;
        List<PractitionersEntity> practitionersEntityList = new ArrayList<PractitionersEntity>();
        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            throw new Exception("上传文件格式不正确");
        }
        boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        Sheet sheet = wb.getSheetAt(0);
        if(sheet!=null){
            notNull = true;
        }
        PractitionersEntity practitionersEntity;
        for (int r = 1; r <= sheet.getLastRowNum(); r++) {
            Row row = sheet.getRow(r);
            if (row == null){
                continue;
            }

            practitionersEntity = new PractitionersEntity();
            row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
            String name = row.getCell(0).getStringCellValue();
            if(name == null || name.isEmpty()){
                throw new Exception("导入失败(第"+(r+1)+"行,姓名未填写)");
            }
            row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
            String corporateId = row.getCell(1).getStringCellValue();
            if(corporateId == null|| corporateId.isEmpty()){
                throw new Exception("导入失败(第"+(r+1)+"行,公司名称未填写)");
            }
            row.getCell(2).setCellType(Cell.CELL_TYPE_STRING);
            String job = row.getCell(2).getStringCellValue();
            if(job == null || job.isEmpty()){
                throw new Exception("导入失败(第"+(r+1)+"行,职务未填写)");
            }
            row.getCell(3).setCellType(Cell.CELL_TYPE_STRING);
            String idCard = row.getCell(3).getStringCellValue();
            if(idCard == null || idCard.isEmpty()){
                throw new Exception("导入失败(第"+(r+1)+"行,身份证号码未填写)");
            }
            row.getCell(4).setCellType(Cell.CELL_TYPE_STRING);
            String phone = row.getCell(4).getStringCellValue();
            if(phone == null || phone.isEmpty()){
                throw new Exception("导入失败(第"+(r+1)+"行,联系电话未填写)");
            }

            row.getCell(5).setCellType(Cell.CELL_TYPE_STRING);
            String addr = row.getCell(5).getStringCellValue();
            if(addr == null || addr.isEmpty()){
                throw new Exception("导入失败(第"+(r+1)+"行,家庭住址未填写)");
            }
            row.getCell(6).setCellType(Cell.CELL_TYPE_STRING);
            String entryTime = row.getCell(6).getStringCellValue();
            Date entryTime1 = dataFormat.parse(entryTime);
            if(entryTime1 == null){
                throw new Exception("导入失败(第"+(r+1)+"行,入职时间未填写)");
            }
            row.getCell(7).setCellType(Cell.CELL_TYPE_STRING);
            String leaveTime = row.getCell(7).getStringCellValue();
            Date leaveTime1 = dataFormat.parse(leaveTime);
            if(leaveTime1 == null){
                throw new Exception("导入失败(第"+(r+1)+"行,离职时间未填写)");
            }
            row.getCell(8).setCellType(Cell.CELL_TYPE_STRING);
            String cause = row.getCell(8).getStringCellValue();
            if(cause == null || cause.isEmpty()){
                throw new Exception("导入失败(第"+(r+1)+"行,监管事由未填写)");
            }
/*            row.getCell(9).setCellType(Cell.CELL_TYPE_STRING);
            String effState = row.getCell(9).getStringCellValue();
            if(effState == null || effState.isEmpty()){
                throw new Exception("导入失败(第"+(r+1)+"行,监管状态未填写)");
            }*/
            row.getCell(9).setCellType(Cell.CELL_TYPE_STRING);
            String result = row.getCell(9).getStringCellValue();
            if(result == null || result.isEmpty()){
                throw new Exception("导入失败(第"+(r+1)+"行,监管结果未填写)");
            }
            row.getCell(10).setCellType(Cell.CELL_TYPE_STRING);
            String reason = row.getCell(10).getStringCellValue();
            if(reason == null || reason.isEmpty()){
                throw new Exception("导入失败(第"+(r+1)+"行,开除原因未填写)");
            }
            row.getCell(11).setCellType(Cell.CELL_TYPE_STRING);
            String remarks = row.getCell(11).getStringCellValue();
/*            if(remarks == null || remarks.isEmpty()){
                throw new Exception("导入失败(第"+(r+1)+"行,备注未填写)");
            }*/
            row.getCell(12).setCellType(Cell.CELL_TYPE_STRING);
            String subUser = row.getCell(12).getStringCellValue();
            if(subUser == null || subUser.isEmpty()){
                throw new Exception("导入失败(第"+(r+1)+"行,提交人未填写)");
            }
            if(name ==null || corporateId ==null || job==null || phone==null
                    || addr ==null || entryTime1 ==null || leaveTime1==null || cause==null
                    || result ==null || reason==null || remarks==null||subUser==null
            ||idCard==null){
                continue;
            }

            practitionersEntity.setName(name);
            practitionersEntity.setCorporateId(practitionersDao.operationid(corporateId));
            practitionersEntity.setJob(job);
            practitionersEntity.setIdCard(idCard);
            practitionersEntity.setPhone(phone);
            practitionersEntity.setAddr(addr);
            practitionersEntity.setEntryTime(entryTime1);
            practitionersEntity.setLeaveTime(leaveTime1);
            practitionersEntity.setCause(cause);
            practitionersEntity.setEffState(1);
            practitionersEntity.setResult(result);
            practitionersEntity.setReason(reason);
            practitionersEntity.setRemarks(remarks);
            practitionersEntity.setSubTime(new Date());
            practitionersEntity.setUpdateTime(new Date());
            practitionersEntity.setSubUser(practitionersDao.subuser(subUser));
            practitionersEntityList.add(practitionersEntity);
        }

        for (PractitionersEntity practitionersEntityResord : practitionersEntityList) {
            practitionersDao.insert(practitionersEntityResord);
            System.out.println(" 插入 "+practitionersEntityResord);

        }
        return notNull;
    }
}
